package cn.deepmax.spring.cloud.system.sale.service.impl;

import cn.deepmax.spring.cloud.system.sale.entity.Order;
import cn.deepmax.spring.cloud.system.sale.entity.Order_;
import cn.deepmax.spring.cloud.system.sale.repository.OrderRepository;
import cn.deepmax.spring.cloud.system.sale.service.OrderService;
import cn.deepmax.spring.cloud.system.sale.vo.AddOrderRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Transactional
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderRepository orderRepository;


    /**
     * 订单分页筛选
     * @param userId 必传
     * @param productId 条件-商品id
     * @param desc  条件-描述
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Order> findUserOrders(Long userId, Long productId, String desc, Integer page,Integer size) {
        PageRequest pageRequest = PageRequest.of(page, size, new Sort(Sort.Direction.DESC, Order_.id.getName()));
        Specification<Order> conditions = (root,query,cb)->{
            List<Predicate> p = new ArrayList<>();
            Predicate eq1 = cb.equal(root.get(Order_.userId), userId);
            p.add(eq1);
            if(productId!=null){
                p.add(cb.equal(root.get(Order_.productId), productId));
            }
            if(StringUtils.hasText(desc)){
                p.add(cb.like(root.get(Order_.description),"%"+desc+"%"));
            }
            return cb.and(p.toArray(new Predicate[0]));
        };
        return orderRepository.findAll(conditions, pageRequest);
    }

    @Override
    public Order addOrder(AddOrderRequest add) {
        Order o = AddOrderRequest.valueOf(add);
        orderRepository.save(o);
        return o;
    }

    @Override
    public Optional<Order> findOrder(Long userId, Long id) {
        return orderRepository.findByIdAndUserId(id, userId);
    }
}
